import axios from 'axios'
import qs from 'qs'
import { Toast } from 'vant'
import router from '../router'
import store  from '../store'
import md5 from 'js-md5'

// axios.defaults.baseURL = 'http://mapi.17byh.com';
axios.defaults.baseURL = 'http://t.mapi.17byh.com';
// axios.defaults.baseURL = 'http://192.168.19.118/mxhy_api/api/web';
axios.defaults.withCredentials=true;
axios.defaults.crossDomain = true;

var imgUrl=axios.defaults.baseURL;


axios.interceptors.request.use(config => {
    return config
}, error => {
    return Promise.reject(error)
})

axios.interceptors.response.use(response => {
    return response
}, error => {
    Promise.resolve(error.response)
})

var gbox="gbox";
var gboxKey="T*Im$1dAJXS5A1x6pqjJI606J%D89blH";
function objKeySort(obj) { 
	var newkey = Object.keys(obj).sort();
	var newObj = {}; 
	for (var i = 0; i < newkey.length; i++) { 
		newObj[newkey[i]] = obj[newkey[i]]; 
	}
	let arr = newObj;
	let a = "";
	for (let i in arr) {
		a += i + "=" + arr[i] + "&";
	}
    let  str=a.substr(0,a.length-1);
	return md5(str+gboxKey).toLowerCase();
}

function checkStatus(response) {
    if (response.status === 200 || response.status === 304) {
        return response
    }
    return {
        data: {
            code: -404,
            message: response.statusText,
            data: response.statusText,
        }
    }
}

function checkCode(res) {
    if( checkToast(res)==true ||res.data.error==103 ||res.data.error==106){
        return res
    }
    if (res.data.error!== 0) {
        Toast(res.data.msg);
    }
    if(res.data.error==101){
        store.commit("SET_LOGININFO",'');
        router.push({
            path: '/login',
            query: {redirect: router.currentRoute.fullPath}
        })
    }
    return res
}

function checkToast(res){
    let url=['loginstat'];
    let nodata=url.some(function(item){
        return res.request.responseURL.indexOf(item)!==-1
    })
    return nodata;
}
export default {
    post(url, data) {
        data['signKey']=gbox;
        let obj=objKeySort(data);
        data['sign']=obj;
        return axios.post(url,qs.stringify(data)
        ).then(checkStatus).then(checkCode)
    },
    get(url, params) {
        if(!params){
            params={params:{}}
        }
        params.params['signKey']=gbox;
        let obj=objKeySort(params.params);
        params.params['sign']=obj;
        return axios.get(url,params
    ).then(checkStatus).then(checkCode)
    },
    delete(url,params){
        if(!params){
            params={params:{}}
        }
        params.params['signKey']=gbox;
        let obj=objKeySort(params.params);
        params.params['sign']=obj;
        return axios.delete(url,params).then(checkStatus).then(checkCode)
    },
    put(url, data) {
        data['signKey']=gbox;
        let obj=objKeySort(data);
        data['sign']=obj;
        return axios.put(url,qs.stringify(data)
        ).then(checkStatus).then(checkCode)
    },
    imgUrl
}
